<template>
  <div>
    <el-card class="custom-container" shadow="never">
      <el-form :model="swiper"
               ref="adminForm"
               label-width="150px" size="small">

        <el-form-item label="标题：">
          <el-input v-model="swiper.title"></el-input>
        </el-form-item>

        <el-form-item label="轮播图：">
          <el-upload
            class="avatar-uploader"
            action="http://wlgc5.oss-cn-shanghai.aliyuncs.com"
            :show-file-list="false"
            :data="dataObj"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="swiper.imgUrl" :src="swiper.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述：">
          <el-input v-model="swiper.description"></el-input>
        </el-form-item>
        <el-form-item label="链接选择：">
          <el-button @click="choiceGood" :type="swiper.type===0?'success':''">选择商品 <i v-if="swiper.type===0"
                                                                                      class="el-icon-check"></i>
          </el-button>
          <el-button @click="choiceArticle" :type="swiper.type===1?'success':''">选择文章 <i v-if="swiper.type===1"
                                                                                         class="el-icon-check"></i>
          </el-button>
          <div v-show="haveType" style="margin-top: 20px">
            <!--            已选择商品-->
            <div v-if="swiper.type===0">
              <el-table ref="productTable"
                        :data="selectedGoodList"
                        style="width: 100%"
                        v-loading="listLoading"
                        border>
                <el-table-column label="编号" width="100" align="center">
                  <template slot-scope="scope">{{ scope.row.id }}</template>
                </el-table-column>
                <el-table-column label="商品图片" width="120" align="center">
                  <template slot-scope="scope"><img style="height: 80px" :src="$store.getters.store+scope.row.img">
                  </template>
                </el-table-column>
                <el-table-column label="商品名称" align="center">
                  <template slot-scope="scope">
                    <p>{{ scope.row.name }}</p>
                    <p>分类：{{ rowCate(scope.row.categoryId) }}</p>
                    <p>科目：{{ rowSubject(scope.row.subjectId) }} | 库存：{{ scope.row.count }}</p>
                  </template>
                </el-table-column>
                <el-table-column label="价格" width="120" align="center">
                  <template slot-scope="scope">
                    <p>价格：￥{{ scope.row.price }}</p>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!--            已选择文章-->
            <div v-if="swiper.type===1">
              <el-table ref="returnApplyTable"
                        :data="selectedArticleList"
                        style="width: 100%;text-overflow: ellipsis"
                        v-loading="listLoading" border>
                <el-table-column label="文章编号" width="120" align="center">
                  <template style="white-space: nowrap;" slot-scope="scope">{{ scope.row.id }}</template>
                </el-table-column>
                <el-table-column label="图片" width="180" align="center">
                  <template slot-scope="scope">
                    <img :src="$store.getters.store+scope.row.img" width="150" height="80" alt="">
                  </template>
                </el-table-column>
                <el-table-column class-name="wrap" label="文章名称" style="text-overflow: ellipsis" width="180"
                                 align="center">
                  <template style="white-space: nowrap;" slot-scope="scope">{{ scope.row.title }}</template>
                </el-table-column>
                <el-table-column class-name="wrap" label="描述" align="center">
                  <template slot-scope="scope" style="text-overflow: ellipsis;white-space: nowrap;">{{
                      scope.row.description
                    }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div ref="t" style="width: 100%;display: flex;justify-content: center;flex-direction: row">
        <div>
          <el-button style="margin: 0 auto;width: fit-content" type="primary" @click.prevent.native="handle">提交
          </el-button>
        </div>
      </div>
    </el-card>
    <!--    选择商品-->
    <el-dialog
      title="选择商品"
      :visible.sync="goodDialogVisible"
      width="80%" style="margin-top: -10vh">
      <el-card class="filter-container" shadow="never">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
          <el-button
            style="float: right"
            @click="handleGoodSearchList()"
            type="primary"
            size="small">
            查询结果
          </el-button>
          <el-button
            style="float: right;margin-right: 15px"
            @click="handleGoodResetSearch()"
            size="small">
            重置
          </el-button>
        </div>
        <div style="margin-top: 15px">
          <el-form :inline="true" :model="goodListQuery" size="small" label-width="140px">
            <el-form-item label="输入搜索：">
              <el-input style="width: 203px" v-model="goodListQuery.keyword" placeholder="商品名称"></el-input>
            </el-form-item>
            <el-form-item label="书籍分类：">
              <el-cascader
                clearable
                @change="getSubjectList"
                v-model="selectProductCateValue"
                :options="productCateOptions">
              </el-cascader>
            </el-form-item>
            <el-form-item label="书籍科目：">
              <el-select v-model="goodListQuery.subjectId" placeholder="请选择科目" clearable>
                <el-option
                  v-for="item in subjectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <el-table ref="productTable"
                :data="goodList"
                style="width: 100%"
                :v-loading="goodListLoading"
                border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="商品图片" width="120" align="center">
          <template slot-scope="scope"><img style="height: 80px" :src="$store.getters.store+scope.row.img"></template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.name }}</p>
            <p>分类：{{ rowCate(scope.row.categoryId) }}</p>
            <p>科目：{{ rowSubject(scope.row.subjectId) }} | 库存：{{ scope.row.count }}</p>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template slot-scope="scope">
            <p>价格：￥{{ scope.row.price }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="goodChoice(scope.$index, scope.row)">选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleGoodSizeChange"
        @current-change="handleGoodCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="goodListQuery.pageSize"
        :page-sizes="[5,10,15,20]"
        :current-page.sync="goodListQuery.pageNum"
        align="center"
        style="margin-top: 20px"
        :total="total">
      </el-pagination>
    </el-dialog>
    <!--    选择文章-->
    <el-dialog
      title="选择文章"
      :visible.sync="articleDialogVisible"
      width="80%" style="margin-top: -10vh">
      <el-card class="filter-container" shadow="never">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
          <el-button
            style="float: right"
            @click="handleArticleSearchList()"
            type="primary"
            size="small">
            查询结果
          </el-button>
          <el-button
            style="float: right;margin-right: 15px"
            @click="handleArticleResetSearch()"
            size="small">
            重置
          </el-button>
        </div>
        <div style="margin-top: 15px">
          <el-form :inline="true" :model="articleQueryList" size="small" label-width="140px">
            <el-form-item label="输入搜索：">
              <el-input style="width: 203px" v-model="articleQueryList.keyword" placeholder="文章名称"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <el-table ref="productTable"
                :data="articleList"
                style="width: 100%"
                :v-loading="articleListLoading"
                border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="封面图片" width="120" align="center">
          <template slot-scope="scope"><img style="height: 80px" :src="$store.getters.store+scope.row.img"></template>
        </el-table-column>
        <el-table-column class-name="wrap" label="描述" align="center">
          <template slot-scope="scope" style="text-overflow: ellipsis;white-space: nowrap;">{{
              scope.row.title
            }}
          </template>
        </el-table-column>
        <el-table-column class-name="wrap" label="描述" align="center">
          <template slot-scope="scope" style="text-overflow: ellipsis;white-space: nowrap;">{{
              scope.row.description
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="articleChoice(scope.$index, scope.row)">选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleArticleSizeChange"
        @current-change="handleArticleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="goodListQuery.pageSize"
        :page-sizes="[5,10,15,20]"
        :current-page.sync="goodListQuery.pageNum"
        align="center"
        style="margin-top: 20px"
        :total="total">
      </el-pagination>
    </el-dialog>
  </div>

</template>

<script>
import {policy} from "@/api/oss";
import {fetchList, getCategoryListAll, getSubjectAll} from "@/api/product";
import {getCategoryTree} from "@/api/productCate";
import {getBook, getSubjectList} from "@/api/book";
import {fetchListArticle, getArticle} from "@/api/returnArticle";
import {createSwiper, swiperGet, updateSwiper} from "@/api/swiper";

const defaultSwiper = {
  id: null,
  imgUrl: '',
  bid: 0, //书籍ID
  aid: 0, // 文章ID
  state: 0,
  type: null, // 0 商品  | 1 文章
  creatorId: 0, // 创建管理员ID
  description: '',
  title: ''
}

const goodsDefaultListQuery = {
  keyword: null,
  pageNum: 1,
  pageSize: 5,
  state: 1,
  recommend: null,
  categoryId: null,
  subjectId: null,
  count: null,

};


const articleDefaultListQuery = {
  pageNum: 1,
  pageSize: 5,
  keyword: null
}
export default {
  name: "swiperDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      id: null,
      swiper: Object.assign({}, defaultSwiper),
      dataObj: {},
      subjectList: [],
      cateList: [],
      listLoading: false,
      goodDialogVisible: false,
      goodListQuery: Object.assign({}, goodsDefaultListQuery),
      selectProductCateValue: null,
      productCateOptions: [],
      subjectOptions: [],
      goodList: [],
      goodListLoading: false,
      total: 0,
      selectedGoodList: [],
      articleDialogVisible: false,
      articleListLoading: false,
      articleList: [],
      articleQueryList: Object.assign({}, articleDefaultListQuery),
      selectedArticleList: []
    }
  },
  computed: {
    haveType() {
      if (this.swiper.type === 0 || this.swiper.type === 1)
        return true;
    }
  },
  created() {
    getSubjectAll().then(res => {
      this.subjectList = res.data;
    })
    getCategoryListAll().then(res => {
      this.cateList = res.data;
    })
    this.getProductCateList()
    if (this.isEdit) {
      this.id = this.$route.query.id
      swiperGet(this.id).then(res => {
        this.swiper = res.data
        console.log(res.data)
        if (this.swiper.type === 0) {
          this.selectedGoodList = [this.swiper.book]
        } else if (this.swiper.type === 1) {
          this.selectedArticleList = [this.swiper.article]
        }
      })
    }
  },
  methods: {
    handle() {
      if (this.isEdit) {
        updateSwiper(this.swiper).then(res => {
          this.$message.success(res.message)
        })
      } else {
        // console.log(this.swiper)
        this.swiper.id = null
        createSwiper(this.swiper).then(res => {
          this.$message.success(res.message)
        })
      }
    },
    /**
     * 选择商品
     */
    choiceGood() {
      this.goodDialogVisible = true
      this.getGoodList()
    },
    /**
     * 选择文章
     */
    choiceArticle() {
      this.articleDialogVisible = true
      this.getArticleList()
    },
    //上传 start
    beforeUpload(file) {
      // const isImg = file.type === 'image/jpeg';
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);

      const whiteList = ["png", "jpeg", "jpg"];

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error("上传文件只能是" + whiteList.join(',') + "格式");
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }

      let _self = this;

      return new Promise((resolve, reject) => {
        policy().then(response => {
          _self.dataObj.policy = response.data.policy;
          _self.dataObj.signature = response.data.signature;
          _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
          _self.dataObj.key = response.data.dir + '/${filename}';
          _self.dataObj.dir = response.data.dir;
          _self.dataObj.host = response.data.host;
          // _self.dataObj.callback = response.data.callback;
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    },
    handleUploadSuccess(res, file) {
      console.log(res)
      let url = this.dataObj.host + '/' + this.dataObj.dir + '/' + file.name;
      this.swiper.imgUrl = url
    },
    //上传 End

    //商品相关 start
    ...{
      rowSubject(val) {
        const filter = this.subjectList.filter(item => item.id == val);
        if (filter.length > 0)
          return filter[0].name
      },
      rowCate(val) {
        const cateArr = []
        const filter = this.cateList.filter(item => item.id === val);
        if (filter && filter.length > 0 && filter[0] !== undefined) {
          cateArr.unshift(filter[0].name);
          if (filter[0].parentId !== 0) {
            this.appendCateFather(cateArr, filter[0].parentId)
          }
        }
        if (cateArr.length > 1) {
          return cateArr.join(' | ')
        } else if (cateArr.length === 1) {
          return cateArr[0]
        }
        return '';
      },
      appendCateFather(cateArr, val) {
        const filter = this.cateList.filter(item => item.id === val);
        if (filter && filter.length > 0 && filter[0] !== undefined) {
          cateArr.unshift(filter[0].name);
          if (filter[0].parentId !== 0) {
            this.appendCateFather(cateArr, filter[0].parentId)
          }
        }
      },
      getProductCateList() {
        getCategoryTree().then(response => {
          let list = response.data;
          this.productCateOptions = [];
          for (let i = 0; i < list.length; i++) {
            let children = [];
            if (list[i].children != null && list[i].children.length > 0) {
              for (let j = 0; j < list[i].children.length; j++) {
                children.push({label: list[i].children[j].name, value: list[i].children[j].id});
              }
            }
            this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
          }
        });
      },
      handleGoodResetSearch() {
        this.selectProductCateValue = [];
        this.goodListQuery = Object.assign({}, goodsDefaultListQuery);
      },
      handleGoodSearchList() {
        this.goodListQuery.pageNum = 1;
        this.getGoodList();
      },
      getSubjectList(val) {
        const categoryId = val[val.length - 1];
        this.subjectOptions = [];
        this.goodListQuery.categoryId = null;
        if (val.length > 0) {
          this.goodListQuery.categoryId = categoryId;
          getSubjectList(categoryId).then(
            response => {
              let subjectList = response.data;
              for (let i = 0; i < subjectList.length; i++) {
                this.subjectOptions.push({label: subjectList[i].name, value: subjectList[i].id});
              }
            }
          )
        }
      },
      getGoodList() {
        this.goodListLoading = true;
        fetchList(this.goodListQuery).then(response => {
          this.goodListLoading = false;
          this.goodList = response.data.list;
          this.total = response.data.total;
        });
      },
      handleGoodSizeChange(val) {
        this.goodListQuery.pageNum = 1;
        this.goodListQuery.pageSize = val;
        this.getGoodList();
      },
      handleGoodCurrentChange(val) {
        this.goodListQuery.pageNum = val;
        this.getGoodList();
      },
      goodChoice(index, row) {
        // console.log(row)
        this.swiper.type = 0
        this.swiper.bid = row.id
        this.swiper.aid = 0
        this.getProduct()
        this.goodDialogVisible = false;
      },
      getProduct() {
        if (this.swiper.type === 0) {
          getBook(this.swiper.bid).then(res => {
            this.selectedGoodList = [res.data]
          })
        }
      }
    },

    //文章相关
    ...{
      handleArticleSearchList() {
        this.articleQueryList.pageNum = 1;
        this.getArticleList();
      },
      getArticleList() {
        this.articleListLoading = true
        this.articleListLoading = true;
        fetchListArticle(this.articleQueryList).then(response => {
          this.articleList = response.data.list
          this.total = response.data.total
          this.articleListLoading = false
        });
      },
      handleArticleResetSearch() {
        this.articleQueryList = Object.assign({}, articleDefaultListQuery)
      },
      handleArticleSizeChange(val) {
        this.articleQueryList.pageNum = 1;
        this.articleQueryList.pageSize = val;
        this.getArticleList();
      },
      handleArticleCurrentChange(val) {
        this.articleQueryList.pageNum = val;
        this.getArticleList();
      },
      articleChoice(index, row) {
        this.swiper.type = 1
        this.swiper.aid = row.id
        this.swiper.bid = 0
        this.getArticle()
        this.articleDialogVisible = false;
      },
      getArticle() {
        if (this.swiper.type === 1) {
          getArticle(this.swiper.aid).then(res => {
            this.selectedArticleList = [res.data]
          })
        }
      }
    },


  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  /*width: 178px;*/
  height: 178px;
  display: block;
}

.custom-container {
  padding: 35px 35px 15px 35px;
  margin: 20px auto;
  width: 95%;
}
</style>
